#!/bin/env python

#from pysqlite2 import dbapi2 as sqlite
import sqlite
from twisted.internet import reactor
from twisted.web import proxy, server, resource

# system imports
import urlparse

class ExtendedResource(resource.Resource):
    def __init__(self, host, port, path):
        resource.Resource.__init__(self)
        self.host = host
        self.port = port
        self.path = path

    def getChild(self, path, request):
        if path == 'history.xml':
            return HistoryResource()


class UriQuery(dict):
    '''
    >>> query_string = 'num=100&q=twisted+python&btnG=Search'
    >>> query = UriQuery(query_string)
    >>> query['q']
    'twisted+python'
    >>> k = query.keys()
    >>> k.sort();k
    ['btnG', 'num', 'q']
    >>> v = query.values()
    >>> v.sort();v
    ['100', 'Search', 'twisted+python']
    '''
    def __init__(self, query):
        self.query = query
        if query:
            query_dict = dict([x.split('=') for x in query.split('&') ])
            self.update(query_dict)
            for key, val in query_dict.items():
                setattr(self, key, val)

def format_date(timestamp):
    import time
    return time.strftime("%Y-%m-%d %H:%M",time.gmtime(timestamp))

                
class HistoryResource(resource.Resource):
    def render(self, request):
        query = UriQuery(urlparse.urlparse(request.uri)[4])
        self.stockid=query['stockid']
        self.from_date=query['from_date']
        self.to_date=query['to_date']

        rtn = 'generar el historico para %s desde %s hasta %s' % (self.stockid, self.from_date, self.to_date)


        # Create connection... 
        db = sqlite.connect('historic2.db')
        # ...which blocks for an unknown amount of time 
 
        # Create a cursor 
        cursor = db.cursor() 
 
        # Do a query...
        sql="SELECT * FROM stock_history WHERE stockid=%s" % self.stockid
        cursor.execute(sql)
        
        print sql
        rtn = '''<ResultSet>
        <Stock id="%s">
        ''' % self.stockid
        
        for row in cursor.fetchall():
            rtn += '''
        <Point>
            <Date>%s</Date>
            <Price>%s</Price>            
            <Shares>%s</Shares>            
            <Buzz>%s</Buzz>            
        </Point>
        ''' % (format_date(row[1]),row[2],row[3], row[4])

        rtn += '''
        </Stock>
        </ResultSet>
        '''
        return rtn

class MiReverseProxyResource(proxy.ReverseProxyResource):
    """Resource that renders the results gotten from another server

    Put this resource in the tree to cause everything below it to be relayed
    to a different server.
    """

    def __init__(self, host, port, path):
        proxy.ReverseProxyResource.__init__(self, host, port, path)

    def getChild(self, path, request):        
        if path == 'extended':
            return ExtendedResource(self.host, self.port, self.path+'/'+path)
        else:
            return proxy.ReverseProxyResource(self.host, self.port, self.path+'/'+path)



site = server.Site(MiReverseProxyResource('buzz.research.yahoo.com', 80, ''))
## Probar con:
# http://localhost:8080/bk/rest/prices.xml
# http://localhost:8080/bk/rest/account.xml?login=ncesar&password=seguridad
# http://localhost:8080/extended/history.xml?stockid=42&from_date=10&to_date=999
reactor.listenTCP(8080, site)
reactor.run()
